<script setup>
import { ref, computed } from 'vue'
import TaskItem from './TaskItem.vue'
import TaskForm from './TaskForm.vue'
import { useTaskStore } from '../../stores/taskStore'

const props = defineProps({
  tasks: {
    type: Array,
    required: true
  },
  title: {
    type: String,
    default: '任务列表'
  },
  emptyMessage: {
    type: String,
    default: '暂无任务'
  }
})

const taskStore = useTaskStore()
const editingTask = ref(null)
const showTaskForm = ref(false)

// 显示编辑表单
const showEditForm = (task) => {
  editingTask.value = { ...task }
  showTaskForm.value = true
}

// 保存任务
const saveTask = (taskData) => {
  if (editingTask.value) {
    taskStore.updateTask(editingTask.value.id, taskData)
  }
  
  editingTask.value = null
  showTaskForm.value = false
}

// 取消编辑
const cancelEdit = () => {
  editingTask.value = null
  showTaskForm.value = false
}

// 过滤已完成和未完成的任务
const incompleteTasks = computed(() => {
  return props.tasks.filter(task => !task.completed)
})

const completedTasks = computed(() => {
  return props.tasks.filter(task => task.completed)
})

// 是否显示已完成的任务
const showCompleted = ref(false)
</script>

<template>
  <div class="task-list">
    <h2 class="text-h6 mb-4">{{ title }}</h2>
    
    <!-- 未完成任务列表 -->
    <div v-if="incompleteTasks.length > 0" class="mb-4">
      <TaskItem 
        v-for="task in incompleteTasks" 
        :key="task.id" 
        :task="task"
        @edit="showEditForm(task)"
        class="mb-2"
      />
    </div>
    
    <!-- 已完成任务折叠面板 -->
    <div v-if="completedTasks.length > 0" class="mt-4">
      <v-btn
        variant="text"
        density="comfortable"
        class="text-capitalize mb-2"
        @click="showCompleted = !showCompleted"
      >
        <v-icon :icon="showCompleted ? 'mdi-chevron-down' : 'mdi-chevron-right'" class="mr-1"></v-icon>
        已完成 ({{ completedTasks.length }})
      </v-btn>
      
      <div v-if="showCompleted">
        <TaskItem 
          v-for="task in completedTasks" 
          :key="task.id" 
          :task="task"
          @edit="showEditForm(task)"
          class="mb-2"
        />
      </div>
    </div>
    
    <!-- 暂无任务提示 -->
    <v-card
      v-if="incompleteTasks.length === 0 && completedTasks.length === 0"
      variant="outlined"
      class="pa-4 text-center"
    >
      <v-icon size="large" color="grey" class="mb-2">mdi-check-circle-outline</v-icon>
      <div class="text-body-1 text-grey">{{ emptyMessage }}</div>
    </v-card>
    
    <!-- 任务编辑表单 -->
    <v-dialog v-model="showTaskForm" max-width="600">
      <TaskForm 
        v-if="editingTask"
        :task="editingTask"
        @save="saveTask"
        @cancel="cancelEdit"
      />
    </v-dialog>
  </div>
</template>

<style scoped>
.task-list {
  max-width: 100%;
}
</style> 